package com.abc.scholarship.config.security.service;


import com.abc.scholarship.domain.entity.Menu;
import com.abc.scholarship.domain.entity.User;
import com.abc.scholarship.service.MenuService;
import com.abc.scholarship.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用根据用户名查询用户信息的方法
        User user = userService.findUserByUsername(username);
        // 对象为空 认证失败
        if(user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 查询用户的拥有的权限列表
        List<Menu> menuList = menuService.findMenuListByUserId(user.getId());
        // 获取权限编码
        List<String> collect = menuList.stream()
                .filter(item -> item !=null)
                .map(item -> item.getCode()).filter(item -> item !=null)
                .collect(Collectors.toList());
        // 转换成数组
        String[] strings = collect.toArray(new String[collect.size()]);
        // 设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        user.setAuthorities(authorityList);
        // 设置菜单列表
        user.setMenuList(menuList);
        return user;
    }
}
